<?php if (!defined("_ECRIRE_INC_VERSION")) return;
/**
 * Aloha Cart
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage alohacart
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/AlohaCart
 */

include_spip('functions/pdk_common');

function formulaires_alohacart_cart_order_verifier_dist(){
	$erreurs = array();
	   
    $cart = pdk_load_class('Alohacart','classes');
	$currency_mdl = pdk_load_class('CurrencyModel','classes');
    $order_mdl = pdk_load_class('AlohacartOrderModel','classes');
    $client_mdl = pdk_load_class('AlohacartClientModel', 'classes');//new ClientModel();
    $auteur_mdl = pdk_load_class('PdkAuteurModel', 'classes');
    $product_mdl = pdk_load_class('ProductModel', 'classes');
    
    //Order validation
    $data = $order_mdl->form_data_from_array($_REQUEST);    
    $order_mdl->validate($data, $erreurs);
    
    //Client validation
    $data = $client_mdl->form_data_from_array($_REQUEST); 
	$client_mdl->validate($data, $erreurs);    
	
	// If client wants to register, check wether such auteur already exists
    if (_request('register_me') and
		$auteur_mdl->get_total("email='".mysql_real_escape_string(_request('email'))."'", "statut='".$client_mdl->registered_statut."'")>0)
        $erreurs['email'] = _T('alohacart:user_with_email_exists');
    
	if ($erreurs)
        $erreurs['message_erreur'] = _T('pdk:validation_message_error');
    
    //Cart validation:
    if (!$cart->CountProducts()>0)
        $erreurs['message_erreur'] = _T('alohacart:cart_is_empty');
        
    $shipping_cost=0;
	if ($id_shipping = intval($_REQUEST['id_shipping'])) {
		$extension_mdl = pdk_load_class('AlohacartExtensionModel','classes');
		$shipping_extension = $extension_mdl->GetExtensionClassByID($id_shipping);
		$shipping_cost = $currency_mdl->ConvertPriceToCurrentCurrency($shipping_extension->GetCost());
	}
	if (($cart->CountPrice()+$shipping_cost)<lire_config('alohacart/order_total_price_min'))
        $erreurs['message_erreur'] = _T('alohacart:min_total_price');
    //Check products quantities in stock
    if (lire_config('alohacart/config_consider_quantity')) {
        $cart_products = $cart->GetProducts();
        if (is_array($cart_products))
        foreach ($cart_products as $array=>$value) {
		   $id_article = $value[0];
		   $quantity = $value[1];
           $product = $product_mdl->select_by_id($id_article);
           if ($quantity > $product['quantity']) {
               $erreurs['message_erreur'] = "<script>show_dialog('not_enough_products');</script>";
               $cart->Updateproduct($id_article, $product['quantity']);
           }
        }
    }
    
	return $erreurs;
}
